﻿using System;
using System.Collections.Generic;
using SdmxMl.Structure;

using System.Text;

namespace SasPlugIn.DB
{
    /// <summary>
    /// Class holding Associated Codelist(s) for one DB table column
    /// </summary>
    public class DbColumnAttachedCodelist
    {
        #region Properties

        /// <summary> SDMX Format associated to codelist</summary>
        public TextFormatType TFormat { get; private set; }


        /// <summary> Table name to use</summary>
        public string Name { get; set; }

        /// <summary> Header colum name to use</summary>
        public string ColName { get; private set; }

        /// <summary>Main codelist associated</summary>
        public CodeListType CltMain { get; private set; }

        /// <summary>Secondary codelist associated</summary>
        public CodeListType CltSecondary { get; private set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Simple C'tor with column name, assumes text format and default length
        /// </summary>
        /// <param name="colName"> Column name</param>
        public DbColumnAttachedCodelist(string colHeadName, CodeListType mainCodelist, TextFormatType tft) : this(colHeadName, mainCodelist, null, tft) { }


        /// <summary>C'tor</summary>
        /// <param name="colName">column name</param>
        /// <param name="maxLen">column text max length</param>
        public DbColumnAttachedCodelist(string colHeadName, CodeListType mainCodelist, CodeListType secondCodelist, TextFormatType tft)
        {
            if (mainCodelist == null)
                throw new ArgumentException();
            TFormat = tft;
            CltMain = mainCodelist;
            CltSecondary = secondCodelist;
            ColName = colHeadName == null ? "Unknown" : colHeadName;

            // Default Name
            Name = CltMain.Id.StartsWith("CL_") ? CltMain.Id.Substring(3) : CltMain.Id;
        }

        #endregion

        #region Composed codelist access

        /// <summary> Provides codelist to operate in column. </summary>
        /// <remarks> Can be a codelist composed from main and secondary</remarks>
        /// <returns>the codelist to associate to the column</returns>
        public CodeListType GetCodelist()
        {
            CodeListType clt = CltMain;

            // Do we need to merge codes ?
            if (CltSecondary != null)
            {
                clt = new CodeListType();
                clt.Id = CltMain.Id;

                // Merge codes of the two codelists
                clt.CodeList.AddRange(CltMain.CodeList.ToArray());
                clt.CodeList.AddRange(CltSecondary.CodeList.ToArray());
            }

            return clt;
        }
        #endregion

    }
}
